<script lang="ts">
  import { create_draw } from "$lib/api/board/board_draw";
  import { boardStore } from "$lib/stores/board.svelte";
  import { userStore } from "$lib/stores/user.svelte";
  import { request } from "$lib/utils/request";
  import { Modal } from "@skeletonlabs/skeleton-svelte";
  import { X } from "lucide-svelte";
  import { getContext } from "svelte";
  import type { Store as ToastStore } from "@zag-js/toast";
  import { openBoardDrawWindow } from "$lib/utils/window";

  const toast: ToastStore = getContext("toast");

  interface ModalProps {
    onClose: () => void;
  }
  let props: ModalProps = $props();

  let drawName = $state("");

  async function createDraw() {
    const res = await request(
      create_draw({
        session_id: userStore.userSession,
        board_id: boardStore.curBoardId,
        basic_info: {
          draw_name: drawName,
        },
      }),
    );
    boardStore.drawVersion += 1;
    await openBoardDrawWindow(boardStore.curBoardId, res.draw_id);
    toast.create({
      title: "成功",
      description: "创建画稿成功!",
      type: "success",
    });
    props.onClose();
  }
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      props.onClose();
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">创建画稿</h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => props.onClose()}
      >
        <X />
      </button>
    </header>

    <main>
      <label class="label relative p-2">
        <span class="label-text">名称</span>
        <input
          class="input rounded-none bg-surface-100-900 text-surface-900-100"
          type="text"
          placeholder="请输入画稿名称"
          bind:value={drawName}
        />
      </label>
    </main>

    <footer class="flex justify-end gap-4">
      <button
        type="button"
        class="btn preset-tonal"
        onclick={() => props.onClose()}>取消</button
      >
      <button
        type="button"
        class="btn preset-filled-primary-900-100"
        disabled={drawName.trim() == ""}
        onclick={() => {
          createDraw();
        }}
      >
        创建
      </button>
    </footer>
  {/snippet}
</Modal>
